<template>
  <div>
    <div ref="chartRef" :style="{ height, width }"></div>
    <div class="custom-floating-div-top">
      <h2>{{ recordRef.name }}</h2>
      <!--     <div style="position: absolute;top: 1%;right: 0px;">
             点位选择：
             <JDictSelectTag @change="point"   placeholder="温度" :dictCode="telemetryValue" :showChooseOption="false" />
           </div>-->
      <a-range-picker @change="onChangeRangeDate"  show-time />
      点位选择：
      <JDictSelectTag @change="point"   placeholder="温度" :dictCode="telemetryValue" :showChooseOption="false" />
      <a-button style="left: 10px" type="primary" @click="search"> 搜索 </a-button>
      <a-button style="left: 10px" type="primary" @click="hourTimeExportXls"> 导出 </a-button>
    </div>
    <!--   <div class="custom-floating-div-left">
    &lt;!&ndash;     <a-date-picker
           :allowClear="false"
           v-model="startValue"
           format="YYYY-MM-DD"
           placeholder="Start"
         />
         <span> &nbsp;~&nbsp; </span>

         <a-date-picker
           :allowClear="false"
           v-model="endValue"
           format="YYYY-MM-DD"
           placeholder="End"
         />&ndash;&gt;

    &lt;!&ndash;     <div class="custom-floating-div-time">
           <a class="custom-button">一年</a>
           <a class="custom-button">三月</a>
           <a class="custom-button">一月</a>
           <a class="custom-button">七天</a>
           <a class="custom-button">三天</a>
           <a class="custom-button">一天</a>
         </div>&ndash;&gt;
       </div>-->
  </div>
</template>
<script lang="ts">
import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
import {defineComponent, PropType, reactive, Ref, ref, watchEffect} from 'vue';
import {useECharts} from '/@/hooks/web/useECharts';
import {GaugeChart} from 'echarts/charts';
import {cloneDeep} from 'lodash-es';
import {useRouter} from 'vue-router'
import {defHttp} from "@/utils/http/axios";
import {useMessage} from "@/hooks/web/useMessage";
import {XLSX_FILE_SUFFIX, XLSX_MIME_TYPE} from "@/hooks/system/useMethods";

export default defineComponent({
  name: 'HourTimeLine',
  components:{
    JDictSelectTag,
  },
  props: {
    chartData: {
      type: Object as PropType<Object>,
      default: () => [],
    },
    option: {
      type: Object,
      default: () => ({}),
    },
    width: {
      type: String as PropType<string>,
      default: '100%',
    },
    height: {
      type: String as PropType<string>,
      default: 'calc(80vh)',
    },
    detailParam: {
      type: String as PropType<string>,
    }
  },
  setup(props) {
    const { createMessage } = useMessage();
    const startValue = ref();
    const endValue  = ref();
    //const data = [["2000-06-05", 3], ["2000-06-06", 3.2], ["2000-06-07", 5], ["2000-06-08", 3.1], ["2000-06-09", 3.6], ["2000-06-10", 3.2], ["2000-06-11", 3.7], ["2000-06-12", 2.5], ["2000-06-13", 2.0], ["2000-06-14", 2.6], ["2000-06-15", 2.4], ["2000-06-16", 2.5], ["2000-06-17", 2.3], ["2000-06-18", 3.4], ["2000-06-19", 3.4], ["2000-06-20", 4.0], ["2000-06-21", 1.0], ["2000-06-22", 1.6], ["2000-06-23", 2.3], ["2000-06-24", 2.8], ["2000-06-25", 2.9], ["2000-06-26", 3.4], ["2000-06-27", 3.5], ["2000-06-28", 4.0], ["2000-06-29", 3.7], ["2000-06-30", 4.6], ["2000-07-01", 5.6], ["2000-07-02", 5.1], ["2000-07-03", 2.3], ["2000-07-04", 3.0], ["2000-07-05", 2.0], ["2000-07-06", 3.0], ["2000-07-07", 3.0], ["2000-07-08", 3.1], ["2000-07-09", 3.3], ["2000-07-10", 3.5], ["2000-07-11", 3.7], ["2000-07-12", 3.9], ["2000-07-13", 2.3], ["2000-07-14", 3.6], ["2000-07-15", 3.5], ["2000-07-16", 3.4], ["2000-07-17", 3.3], ["2000-07-18", 3.2], ["2000-07-19", 3.1], ["2000-07-20", 3.3], ["2000-07-21", 3.8], ["2000-07-22", 3.5], ["2000-07-23", 3.7], ["2000-07-24", 3.8]];
    const dateList = ref([]);
    const valueList = ref([]);
    const dataList = ref(Object);
    const chartRef = ref<HTMLDivElement | null>(null);
    const { setOptions, echarts } = useECharts(chartRef as Ref<HTMLDivElement>);
    const recordRef = useRouter().currentRoute._rawValue.query;
    const telemetryValue = ref(recordRef.telemetry);
    const queryDeviceReportList = ref(recordRef.reportUrl);
    const pointValue = ref(recordRef.first_telemetry)
    const option = reactive({
      // Make gradient line here
      visualMap: [
        {
          color: ['#5793f3'],
          show: false,
          type: 'continuous',
          seriesIndex: 0,
        },
        /*{
          show: false,
          type: 'continuous',
          seriesIndex: 1,
          dimension: 0,
          min: 0,
          max: dateList.length - 1
        }*/
      ],
      /*title: [
        {
          left: 'center',
          text: 'Gradient along the y axis'
        },
        {
          top: '55%',
          left: 'center',
          text: 'Gradient along the x axis'
        }
      ],*/
      tooltip: {
        trigger: 'axis'
      },
      xAxis: [
        {
          data: dateList,
          gridIndex: 0,
          axisLabel: {
            /*formatter: function (value, index) {
              // 假设 value 是一个时间戳（毫秒）
              const date = new Date(value);

              // 格式化日期为 'yyyy-MM-dd'
              const formattedDate = date.getFullYear() + '-' +
                ('0' + (date.getMonth() + 1)).slice(-2) + '-' +
                ('0' + date.getDate()).slice(-2);

              // 格式化时间为 'HH:00:00'
              const formattedTime = ('0' + date.getHours()).slice(-2) + ':00:00';

              // 使用换行符将日期和时间分开
              return formattedDate + '\n' + formattedTime;
            },*/
            // 可能需要调整文本样式以适应换行
            textStyle: {
              // 例如，设置字体大小为 12
              fontSize: 12
            }
          }
        },
        /*{
          data: dateList,
          gridIndex: 1
        }*/
      ],
      yAxis: [
        {},
        /* {
           gridIndex: 1
         }*/
      ],
      grid: { left: '1%', right: '1%', top: '30   %', bottom: "30 %", containLabel: true },
      series: [
        {
          type: 'line',
          showSymbol: false,
          data: valueList,
        }/*,
        {
          type: 'line',
          showSymbol: false,
          data: valueList,
          xAxisIndex: 1,
          yAxisIndex: 1
        }*/
      ]
    });

    watchEffect(() => {
      props.chartData && initCharts();
    });
    function initCharts() {
      echarts.use(GaugeChart);
      if (props.option) {
        Object.assign(option, cloneDeep(props.option));
      }
      dateList.value = [];
      valueList.value = [];
      option.xAxis[0].data = dataList.value.createTime;
      option.series[0].data = dataList.value[pointValue.value]
      setOptions(option);
    }

    function point(event){

      pointValue.value = event;
      initCharts();
    }
     async function hourTimeExportXls() {
       const isXlsx = true;
       const url = "/yc/web/deviceReport/HourTimeExportXls";
       if (startValue.value == null || endValue.value == null) {
         alert("请选择时间区域")
         return;
       }
       let params = {
         [recordRef.noType]: recordRef.no,
         terminalId: recordRef.terminalId,
         pageNo: 1,
         pageSize: 10000,
         createTime_begin: startValue.value,
         createTime_end: endValue.value
       };
       //update-begin---author:wangshuai---date:2024-01-25---for:【QQYUN-8118】导出超时时间设置长点---
       const data = await defHttp.get({
         url: url,
         params: params,
         responseType: 'blob',
         timeout: 60000
       }, {isTransformResponse: false});
       //update-end---author:wangshuai---date:2024-01-25---for:【QQYUN-8118】导出超时时间设置长点---
       if (!data) {
         createMessage.warning('文件下载失败');
         return;
       }
       let blobOptions = {type: 'application/vnd.ms-excel'};
       let fileSuffix = '.xls';
       if (isXlsx === true) {
         blobOptions['type'] = XLSX_MIME_TYPE;
         fileSuffix = XLSX_FILE_SUFFIX;
       }
       if (typeof window.navigator.msSaveBlob !== 'undefined') {
         window.navigator.msSaveBlob(new Blob([data], blobOptions), name + fileSuffix);
       } else {
         let url = window.URL.createObjectURL(new Blob([data], blobOptions));
         let link = document.createElement('a');
         link.style.display = 'none';
         link.href = url;
         link.setAttribute('download', name + fileSuffix);
         document.body.appendChild(link);
         link.click();
         document.body.removeChild(link); //下载完成移除元素
         window.URL.revokeObjectURL(url); //释放掉blob对象
       }
     }
    async function search() {
      if(startValue.value == null || endValue.value == null){
        alert("请选择时间区域")
        return;
      }
      let params = {
        [recordRef.noType]: recordRef.no,
        terminalId:recordRef.terminalId,
        pageNo: 1,
        pageSize: 10000,
        createTime_begin: startValue.value,
        createTime_end: endValue.value
      };
      dataList.value = await defHttp.get({
        url: "/yc/web/deviceReport/deviceHourTimeLineData",
        params
      });
      initCharts();
    }
    function onChangeRangeDate(value,dateString){
      startValue.value = dateString[0];
      endValue.value = dateString[1];
    }
    return {
      chartRef,
      recordRef,
      point,
      search,
      startValue,
      endValue,
      onChangeRangeDate,
      telemetryValue,
      hourTimeExportXls,
    };
  },
});
</script>
<style>
.custom-floating-div-time {
  position: absolute;
  top: 20%;
  right: 10px;
  width: 30%;
  display: flex;
  justify-content: flex-end; /* 右对齐 */
}
.custom-floating-div-left {
  position: absolute;
  top: 20%;
  left: 10px;
  width: 99%;
}
.custom-floating-div-top{
  position: absolute;
  top: 5%;
  left: 1%;
  right: 1%;
  height: 10%;
}
.custom-button {
  padding: 4px;
  color: #1294f7;
  cursor: pointer;
  border-radius: 4px;
}
</style>
